<template>
    <div class="box">
        <vxe-modal v-model="showDialog" :title="'数据选择列表  '+title" :width="isequipment?800:screenWidth" :height="screenHeight*0.8-50" transfer  show-zoom resize remember lock-scroll :showFooter="true" >
            <el-container>
              <el-aside v-show="sidShow" width="200px" style="padding: 0px !important;">
                <vxe-table show-overflow ref="xTree" size="small" height="600" :show-header="false" :accordion="true" :tree-config="{transform: true, rowField: 'id', parentField: 'parentId', }" :radio-config="{ labelField: 'name' }" :data="TreeData">
                  <vxe-column type="radio" tree-node></vxe-column>
                </vxe-table>
              </el-aside>
              <el-container>
                <el-header style="height: 35px">
                  <el-row>
                    <el-col :sm="24" :md="24">
                      <el-input v-model="keyword" type="search" placeholder="当前表内搜索" size="small" clearable style="width: 200px"   @input="searchEvent"></el-input>
                      <el-button size="small" type="primary" @click="FullSearch">全新搜索</el-button>
                      <vxe-checkbox v-model="showSearch" content="高级搜索" :checked-value="true" :unchecked-value="false"></vxe-checkbox>
                      <vxe-checkbox v-model="hebing" content="字段合并"></vxe-checkbox>
                      <vxe-checkbox v-if="checkedList.length>0" v-model="fenxiang" content="批量分箱"></vxe-checkbox>
                    </el-col>
                    <el-col :sm="24" :md="24" align="right">
                      <div v-if="allowManual">
                        <el-input size="small" placeholder="手动请输入值" v-model="Manual">
                          <el-button slot="append" size="small" type="primary" @click="submit()">确认</el-button>
                        </el-input>
                      </div>
                    </el-col>
                  </el-row>
      
                </el-header>
                <el-main style="padding: 0 10px !important;">
                  <vxe-table border ref="xTable" :data="List"  :height="screenHeight*0.8-250" :loading="loading" size="small" show-overflow :row-config="{isCurrent: true, isHover: true}" @checkbox-change="selectChangeEvent" @checkbox-all="selectAllChangeEvent"  @cell-dblclick="selectrowdbclick">
                    <vxe-column v-if="extend.single" type="radio" width="41"></vxe-column>
                    <vxe-column v-else type="checkbox" width="41"></vxe-column>
                    <vxe-column sortable resizable show-overflow v-for="(it,index) in Fields" :field="it.field" :key="it.keys" :title="it.title" :width="it.width" :visible="it.hidden===0" >
                      <template #edit="{ row }">
                        <vxe-input  v-model="row[it.field] "></vxe-input>
                      </template>
                    </vxe-column>
                  </vxe-table>
                  <vxe-pager
                      background border
                      @page-change="PageChange"
                      :current-page="page.pageNum"
                      :page-sizes="[100, 200, 500, 1000]"
                      :page-size="page.pageSize"
                      :pager-count="5"
                      :total="page.totalResult"
                      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes',  'Total']">
                    </vxe-pager>
                </el-main>
              </el-container>
            </el-container>
            <template #footer style="float: right">
              <div  class="button-m">
                <vxe-button size="small" status="primary" @click="submit()">确定</vxe-button>
                <vxe-button size="small" status="primary" @click="$refs.xTable.clearCheckboxRow()">清除</vxe-button>
                <vxe-button size="small" status="primary" @click="close">取消</vxe-button>
              </div>
            </template>
        </vxe-modal>
        <vxe-modal v-model="showSearch" ref="MS" title="高级搜索:" :width="isequipment?700:screenWidth" height="480" transfer :zIndex="9999" :showFooter="true">
          <vxe-form ref="searchForm" size="small" :data="formData">
            <vxe-form-item v-for="(item,index) in Fields" :title="item.title" :field="item.field" :key="index" :item-render="{}">
              <template #default="{ data }">
                <div v-if="item.searchType===9">
                  <Between :type="item.dataTypeID===4?'date':'text'" v-model="data[item.field]"></Between>
                </div>
                <div v-else>
                  <vxe-input   v-model="data[item.field]" placeholder="请输入条件值"></vxe-input>
                </div>
              </template>
            </vxe-form-item>
          </vxe-form>
            <template #footer style="float: right">
              <div  class="button-m">
                <vxe-button size="small" status="primary" @click="dfQuery">确定</vxe-button>
                <vxe-button size="small" status="primary" @click="$refs.searchForm.reset()">重置</vxe-button>
                <vxe-button size="small" status="primary" @click="closeMS">取消</vxe-button>
              </div>
            </template>
        </vxe-modal>
        <vxe-modal v-model="fenxiang" :title="'分箱列表'" width="600">
          <vxe-input type="Number" placeholder="分箱数量" v-model="fenxiangzong" @input="inputsun"></vxe-input>
          <div style="overflow: auto;height: 400px;">
            <vxe-table
            border
            show-overflow
            :data="checkedList"
            :column-config="{resizable: true}"
            :edit-config="{trigger: 'click', mode: 'cell'}">
            <vxe-column field="送货单号" title="送货单号"></vxe-column>
            <vxe-column field="存货名称" title="存货名称"></vxe-column>
            <vxe-column field="送货数量" title="送货数量"></vxe-column>
            <vxe-column field="fenxiangshulaing" title="分箱数量" :edit-render="{autofocus: '.vxe-input--inner'}">
              <template #edit="{ row }">
                <vxe-input v-model="row.fenxiangshulaing" type="Number"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
          </div>
          <div style="text-align: right;margin-top: 10px;">
            <vxe-button size="small" status="primary" @click="fenxiangqueding">确定</vxe-button>
            <vxe-button size="small" status="primary" @click="()=>{fenxiang=false}">取消</vxe-button>
          </div>
        </vxe-modal>
    </div>
</template>

<script>
import {reactive, ref, toRefs} from "vue"
import XEUtils, {assign} from 'xe-utils'
import {ElMessage} from 'element-plus'
import {getDataGrid} from "/@/api/linkoo/form"
import Between from '/@/views/views/components/between.vue';

export default {
    props:['isequipment'],
    emits:["submit"],
  components:{Between},
    setup(props,ctx) {
        let xTable = ref(null)
        let searchForm = ref(null)
        let fenxiang = ref(false)
        let hebing=ref(false)
        let shulaing = ref(0)
        let fenxiangzong = ref('')
        let state = reactive({
            formData:{},
            showDialog:false,
            isSearch:false,
            Manual: "",
            allowManual:false,
            Data:{},
            loading:false,
            DataGrids:{},
            filterName:'',
            keyword: "",
            fullSearch:false,
            showSearch:false,
            page: {
                pageNum: 1,
                pageSize: 100,
                totalResult: 0,
            },
            Fields:[],
            extend:{single:false},
            DataGridsField:{},
            tableData: [],
            List:[],
            TreeData: [],
            sidShow:false,
            screenHeight: document.body.clientHeight,
          screenWidth: document.body.clientWidth,
            title: "",
          searchType:[{value: 0, label: '不查询'}, {value: 1,operate:'like', label: '快搜'}, {value:2,operate: '=', label: '等于'}, {value: 3,operate:'<>', label: '不等于'},
            {value: 4,operate:'<',label: '小于'}, {value:5,operate: '<=', label: '小于等于'}, {value:6,operate: '>', label: '大于'}, {value: 7,operate:'>=', label: '大于等于'},
            {value: 8,operate:'in', label: '在列表中'}, {value: 9,operate:'between', label: '区间'}]
        })
        const todo =(extend)=>{
            state.extend={single:false}
            state.extend=XEUtils.assign(state.extend,XEUtils.toStringJSON(extend))
            console.log('extend.single',state.extend)
            getdata()
            state.isSearch=false
            state.Manual=''
            if(!state.showDialog)state.showDialog=true
        }
        const inputsun = ()=>{
          checkedList.value.forEach((item,index)=>{
            checkedList.value[index].fenxiangshulaing=fenxiangzong.value
          })
        }
        const getdata = ()=>{
            state.allowManual = false
            if (state.Data.field.allowManual === 1) {
                state.allowManual = true
            }
            state.loading = true
            let tk = state.Data.field.componentID + state.Data.field.fieldName
            if (XEUtils.isEmpty(state.DataGrids[tk]) || state.filterName !== '' || state.isSearch|| state.fullSearch||state.Data.field.componentFilterExpr!=='') {
                const data = {
                    id: state.Data.field.componentID, filter: state.Data.field.componentFilterExpr, fastSearch: state.filterName,
                    tid: state.Data.field.componentType, pageNum: state.page.pageNum, pageSize: 500
                }
                console.log(state.isSearch);
                if (state.isSearch) {
                    let ADS = []
                    XEUtils.objectEach(state.formData, (item, key) => {
                        if (XEUtils.toValueString(item) !== '') {
                        const f = state.Fields.find(item => item.field === key)
                        ADS.push({ key: f['fieldExpr'], val: XEUtils.toValueString(item) })
                        }
                    })
                    data['ADSearch'] = JSON.stringify(ADS)
                }
                console.log(data);
                getDataGrid(data).then(response => {
                  if   (response.data.list === null) response.data.list = []
                    state.page.pageSize = 500
                    state.title = response.data.info.dataGridName
                    state.Fields = []
                    XEUtils.orderBy(response.data.field, 'dispSeq').forEach(_field => {
                        state.Fields.push({
                        keys: _field.dataGridFieldID,
                        field: _field.fieldDispName,
                        title: _field.fieldDispName,
                          dataTypeID: _field.dataTypeID===undefined?1:_field.dataTypeID,
                        width: _field.allowFixedWidth > 0 ? _field.allowFixedWidth : 80,
                        hidden: _field.hidden,
                        searchType: _field.allowLikeSearch,
                        fieldExpr: _field.fieldExpr
                        })
                    })
                    state.DataGridsField[tk] = XEUtils.clone(state.Fields, true)

                    if (response.data.list === null) response.data.list = []
                    if (response.data.list.length === response.data.total) {
                        state.page.pageSize = response.data.total
                    }
                    state.DataGrids[tk] = response.data.list
                    state.tableData = response.data.list
                    state.List = response.data.list.map((row, index) => {
                        XEUtils.objectEach(row, (item, key) => {
                        if (XEUtils.isObject(item)) {
                            const fd = XEUtils.find(response.data.field, it => it.fieldDispName === key)
                            if (fd !== null && fd !== undefined) {
                            row[key] = XEUtils.get(row, fd.fieldExpr)
                            }
                        }
                        })
                        return row
                    })
                    state.page.totalResult = response.data.total
                    xTable.value.resetColumn()
                    state.loading = false
                    state.fullSearch = false

                })
            } else {
                state.tableData = XEUtils.clone(state.DataGrids[tk], true)
                state.List = XEUtils.clone(state.DataGrids[tk], true)
                state.Fields = XEUtils.clone(state.DataGridsField[tk], true)
                xTable.value.resetColumn()
                state.loading = false
            }
        }
        const close=()=>{
            state.showDialog=false
        }
        const PageChange=({currentPage})=> {
            state.page.pageNum = currentPage
            state.fullSearch=true
            getdata()
        }
        const selectrowdbclick=({row})=>{
            xTable.value.setCheckboxRow([row], true)
            submit()
        }
        const submit=()=>{
            let records=[]
            if(state.Manual===''){
                if(state.extend.single){
                    records.push( xTable.value.getRadioRecord())
                }else {
                    records=xTable.value.getCheckboxRecords()
                }

                if(records.length===0){
                  let record=xTable.value.getCurrentRecord()
                  if(record===null ){
                      ElMessage({
                          type: 'info',
                          message: `选择数据或后打勾后再操作!!`,
                      })
                      return false
                  }else{
                      records.push(record)
                  }
                }
            }else{
                const v={}
                const k=JSON.parse(state.Data.field.componentFieldName)[state.Data.field.fieldName]
                v[k['v']]=state.Manual
                records.push(v)
            }
            console.log(records,hebing.value);
            // if(hebing.value==true){
            //   ctx.emit("submit", {data:records,data2:hebing.value});
            // }else{
            //   records.forEach((itemSxm)=>{
            //     ctx.emit("submit", {data: [itemSxm],data2:hebing.value});
            //   })
            // }
            let isfenxiang = records.findIndex(objt => objt.fenxiangshulaing == undefined||objt.fenxiangshulaing == 0);
            ctx.emit("submit", {data: records,data2:hebing.value,C:state.Data.field.fieldName,xiang:isfenxiang == -1?true:false,shu:shulaing.value});
            state.showDialog=false
            state.List=[]
            checkedList.value=[]
        }
        const FullSearch=()=>{
            state.isSearch=false
            state.filterName = XEUtils.trim(XEUtils.toValueString(state.keyword)).toLowerCase().replace(/ /g,'%')
            state.fullSearch=true
            getdata()
        }
        const searchEvent=()=> {
            const filterName = XEUtils.toValueString(state.keyword).trim().toLowerCase()
            if (filterName) {
                // const filterRE = new RegExp(filterName, 'gi')
                const searchProps = Array.from(state.Fields).map(row=>{          return row.field        })
                state.List = state.tableData.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
            } else {
                state.List = state.tableData
            }
        }
        const closeMS=()=>{
            state.isSearch=false
            state.showSearch=false
        }
      const dfQuery = () => {
        state.isSearch=true
        state.showSearch=false

        getdata()
      }
      let checkedList = ref([]) 
      const selectChangeEvent = ({ checked }) => {
        console.log("123");
        const $table = xTable.value
        if ($table) {
          const records = $table.getCheckboxRecords()
          checkedList.value=records
          console.log(checked ? '勾选事件' : '取消事件', records)
        }
      }
      const selectAllChangeEvent = ({ checked }) => {
        const $table = xTable.value
        if ($table) {
          const records = $table.getCheckboxRecords()
          checkedList.value=records
          console.log(checked ? '所有勾选事件' : '所有取消事件', records)
        }
      }
      const fenxiangqueding = ()=>{
        fenxiang.value=false
        submit()
      }
        return{
            xTable,searchForm,dfQuery,selectChangeEvent,checkedList,fenxiangqueding,selectAllChangeEvent,fenxiangzong,inputsun,
            ...toRefs(state),
            todo,
            getdata,
            close,
            selectrowdbclick,
            submit,
            PageChange,
            searchEvent,
            FullSearch,
            closeMS,
            fenxiang,
            hebing,
            shulaing
        }
    }
}
</script>

<style scoped>

</style>